package com.csust.automaticteach.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csust.automaticteach.common.BaseResponse;
import com.csust.automaticteach.common.ResultUtils;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.model.dto.chatsession.AddChatSessionRequest;
import com.csust.automaticteach.model.dto.chatsession.ChatSessionQueryRequest;
import com.csust.automaticteach.model.dto.chatsession.updateChatsessionRequest;
import com.csust.automaticteach.model.entity.Chatsession;
import com.csust.automaticteach.model.entity.GenerateExam;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.vo.chatsession.ChatSessionVO;
import com.csust.automaticteach.model.vo.generateexam.GenerateExamPageVO;
import com.csust.automaticteach.service.ChatsessionService;
import com.csust.automaticteach.service.UserService;
import com.csust.automaticteach.utils.MessageSerializer;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @ClassNameChatSessionController
 * @Description 消息会话控制器
 * @Author钰玟
 * @Date2025/7/9 下午9:02
 * @Version 1.0
 **/
@RestController
@RequestMapping("/chatSession")
@Slf4j
public class ChatSessionController {

    @Resource
    private UserService userService;
    @Resource
    private ChatsessionService chatsessionService;


    @PostMapping("/add")
    public BaseResponse<Long> addChatSession(@RequestBody AddChatSessionRequest addChatSessionRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(addChatSessionRequest == null, ErrorCode.NOT_LOGIN_ERROR);
        String title = addChatSessionRequest.getTitle();
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        Chatsession chatsession = new Chatsession();
        chatsession.setTitle(title);
        chatsession.setUserId(userId);
        boolean saved = chatsessionService.saveOrUpdate(chatsession);
        //主键回显
        Long id = chatsession.getId();
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "创建会话失败");
        return ResultUtils.success(id);
    }


    /**
     * 根据Id获取会话
     *
     * @param id      会话Id
     * @param request 请求
     * @return 会话VO
     */
    @GetMapping("/get/{id}")
    public BaseResponse<ChatSessionVO> getChatSession(@PathVariable("id") long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        QueryWrapper<Chatsession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("userId", userId);
        //查询chatSession对象
        Chatsession chatsession = chatsessionService.getOne(queryWrapper);
        ChatSessionVO chatSessionVO = chatsessionService.getChatSessionVO(chatsession);
        //返回
        return ResultUtils.success(chatSessionVO);
    }

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChatSessionVO>> listChatSessionVOByPage(@RequestBody ChatSessionQueryRequest chatSessionQueryRequest
            , HttpServletRequest request) {
        //校验参数
        ThrowUtils.throwIf(chatSessionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = chatSessionQueryRequest.getCurrent();
        int pageSize = chatSessionQueryRequest.getPageSize();
        User loginUser = userService.getLoginUser(request);
        chatSessionQueryRequest.setUserId(loginUser.getId());
        //分页查询
        Page<Chatsession> chatsessionPage = chatsessionService.page(new Page<>(current, pageSize)
                , chatsessionService.getChatSessionQueryWrapper(chatSessionQueryRequest));
        //构造vo的page对象
        Page<ChatSessionVO> chatSessionVOPage = new Page<>(current, pageSize, chatsessionPage.getTotal());
        //得到vo列表
        List<ChatSessionVO> chatSessionVOList = chatsessionService.getChatSessionVOList(chatsessionPage.getRecords());
        //设置vo列表
        chatSessionVOPage.setRecords(chatSessionVOList);
        //返回
        return ResultUtils.success(chatSessionVOPage);
    }

    /**
     * 根据Id删除会话
     *
     * @param id 会话Id
     * @return 会话VO
     */
    @DeleteMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteChatSession(@PathVariable("id") long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        boolean b = chatsessionService.removeById(id);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新会话
     *
     * @param updateChatsessionRequest 会话更新请求
     * @param request                  请求
     * @return 会话VO
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateChatSession(@RequestBody updateChatsessionRequest updateChatsessionRequest, HttpServletRequest request) {
        //校验参数
        ThrowUtils.throwIf(updateChatsessionRequest == null, ErrorCode.PARAMS_ERROR);
        Boolean b = chatsessionService.updateChatsession(updateChatsessionRequest);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 批量删除会话
     *
     * @param ids 会话Id列表
     * @return 会话VO
     */
    @PostMapping("/delete/batch")
    public BaseResponse<Boolean> batchDeleteChatSession(@RequestBody List<Long> ids) {
        ThrowUtils.throwIf(CollUtil.isEmpty(ids), ErrorCode.PARAMS_ERROR);
        boolean b = chatsessionService.removeBatchByIds(ids);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


}
